/**
 * 
 */
package darwin8086.genetic;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;

import darwin8086.war.Competition;

/**
 * @author Dean
 *
 */
public class Benchmarker {

	String [] subSurvivorDirs = {"dummy/","shooterA/","mpo/","script_kiddie/","XLII/"};
	String originalPath;
	static int numGeneration = 0;
	final int BATTLES = 10;
	final String BENCHMARK_DIR = "benchmark/";
	final double score[][];
	
	public Benchmarker(int generationLength, int numGenerations) {
		File temp = new File("");
		originalPath = temp.getAbsolutePath();
		score = new double[generationLength][numGenerations];
	}
	
	public void StatisticsOut(String filename) throws IOException {
		FileOutputStream out = new FileOutputStream(originalPath+"/"+BENCHMARK_DIR+filename + ".csv");
		PrintStream ps = new PrintStream(out);
		for(int i=0;i<score.length;i++) {
			for(int j=0;j<score[i].length;j++) {
				ps.print(score[i][j] + ",");
			}
			ps.print("\n");
		}
		out.close();
	}
	
	public void BenchmarkGeneration(Generation generation) throws Exception{
		String output = new String();
		String title = "";
		boolean titleWritten = false;		
		for(int i=0;i<subSurvivorDirs.length;i++) {
			ArrayList<Gene> geneMap = (ArrayList<Gene>) generation.geneMap.clone();
			output += subSurvivorDirs[i] + ",";
		    for(int j=0;j<geneMap.size();j++) {
		    	System.out.println("gene: " + j);
		    	if(!titleWritten){
		    		title += "," + "Gene id: " + geneMap.get(j).GetID();
		    	}
				geneMap.get(j).WriteToFile(originalPath+"/"+BENCHMARK_DIR+subSurvivorDirs[i]+"survivors/", "bot0");
				System.out.println(originalPath+"/"+BENCHMARK_DIR+subSurvivorDirs[i]);
				Competition competition = new Competition(originalPath+"/"+BENCHMARK_DIR+subSurvivorDirs[i]+
						"survivors/",originalPath+"/"+BENCHMARK_DIR+subSurvivorDirs[i]+"zombies/");
				competition.setSpeed(2147483647); //maximum int value possible
				competition.runCompetition(BATTLES, 2);
				output += competition.getWarriorRepository().getScore("bot0") +",";
				score[geneMap.get(j).GetID()][numGeneration] += competition.getWarriorRepository().getScore("bot0"); 
			}
		    if(!titleWritten) {
		    	titleWritten = true;
		    	title += "\n";
		    }
		    output += "\n";
		}
		FileOutputStream out = new FileOutputStream(originalPath+"/"+BENCHMARK_DIR+"benchmark" + numGeneration + ".csv");
		PrintStream ps = new PrintStream(out);
		ps.print(title);
		ps.print(output);
		out.close();
		numGeneration++;
	}
	
}
